package com.jj.spb.spring_boot_mybatis.service;

import com.jj.spb.spring_boot_mybatis.entity.Vote;
import com.jj.spb.spring_boot_mybatis.entity.VoteItem;
import com.jj.spb.spring_boot_mybatis.entity.VoteResult;
import com.jj.spb.spring_boot_mybatis.repository.VoteItemRepository;
import com.jj.spb.spring_boot_mybatis.repository.VoteRepository;
import com.jj.spb.spring_boot_mybatis.repository.VoteResultRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class VoteService {
    ArrayList<VoteItem> emptyArray = new ArrayList<>(0);

    @Autowired
    VoteRepository voteRepository;

    @Autowired
    VoteItemRepository voteItemRepository;

    @Autowired
    VoteResultRepository voteResultRepository;

    public List<VoteResult> queryVoteResultByVoteId(long id){
        Optional<List<VoteResult>> result = voteResultRepository.findAllByVoteId(id);
        if(result.isPresent()){
            return result.get();
        }
        return null;
    }

    public boolean existVote(long voteId){
        return voteRepository.existsById(voteId);
    }

    public boolean existVoteItemBySerialNum(long voteId,int serialNum){
        return voteItemRepository.existsByVoteIdAndSerialNum(voteId,serialNum);
    }
    public int findIdByVoteIdAndSerialNum(long voteId,int serialNum){
        return voteItemRepository.findIdByVoteIdAndSerialNum(voteId,serialNum);
    }

    public long saveVote(Vote vote){
        vote = voteRepository.saveAndFlush(vote);
        return vote.getId();
    }

    public Vote findVote(long voteId){
        return voteRepository.findById(voteId).get();
    }

    public long saveVoteItem(VoteItem voteItem){
        voteItem = voteItemRepository.saveAndFlush(voteItem);
        return voteItem.getId();
    }

    public List<VoteItem> findAllVoteItem(long voteId){
        Optional<List<VoteItem>> items = voteItemRepository.findAllByVoteId(voteId);
        if(items.isPresent()){
            return items.get();
        }
        return emptyArray;
    }

    public int addOrUpdateVoteResult(VoteResult result){
        int oldId = voteResultRepository.findIdByVoteIdAndStudentId(result.voteId,result.studentId);
        result.setId(oldId);
        result = voteResultRepository.saveAndFlush(result);
        return result.id;
    }
}
